package com.shanzmoo.merchant.server.api.manager.member;

import com.shanzmoo.db.module.member.domain.dto.CMemberConsumeDTO;
import com.shanzmoo.db.module.member.domain.dto.CMemberRechargeDTO;
import com.shanzmoo.db.module.member.domain.dto.CMemberRefundDTO;
import com.shanzmoo.db.module.member.domain.dto.CMemberScoreConsumeDTO;
import com.shanzmoo.db.module.member.entity.*;
import com.shanzmoo.db.module.member.service.*;
import com.shanzmoo.db.util.TimeUtils;
import com.shanzmoo.merchant.server.api.service.IMemberInnerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 内部调用接口服务
 */
@Service
public class MemberInnerServiceImpl implements IMemberInnerService {
    @Autowired
    private IMemberAccountRecordService memberAccountRecordService;
    @Autowired
    private IMemberMerchantService memberMerchantService;
    @Autowired
    private IMemberCouponService memberCouponService;
    @Autowired
    private IMemberCouponConfigService memberCouponConfigService;
    @Autowired
    private IMemberCardConfigDetailService cardConfigDetailService;
    @Autowired
    private IMemberCardConfigService memberCardConfigService;
    @Autowired
    private IMemberAccountScoreRecordService memberAccountScoreRecordService;
    @Autowired
    private IMemberInfoService memberInfoService;
    /**
     * 账户消费服务
     * 目前都是单体服务，如果失败会直接抛异常，调用方直接根据异常回滚自己的事务/捕获异常
     *
     * @param consumeDTO
     */
    @Transactional(rollbackFor = Throwable.class)
    public Long consume(CMemberConsumeDTO consumeDTO) throws Exception {
        Integer couponId = consumeDTO.getCouponId();
        String orderNo = consumeDTO.getOrderNo();
        Integer memberMerchantId = consumeDTO.getMemberMerchantId();
        Integer activityConfigDetailId = consumeDTO.getActivityConfigDetailId();
        if (activityConfigDetailId!=null && couponId!=null){
            throw new Exception("活动与优惠券不能同时使用");
        }
        Long orderAmt = consumeDTO.getAmt();
        Long realAmt = orderAmt.longValue();
        if (couponId!=null){
            //校验优惠券
            MemberCouponEntity couponEntity = memberCouponService.getById(couponId);
            if (couponEntity.getStatus()!=1){
                throw new Exception("优惠券状态异常");
            }
            Long couponConfigId = couponEntity.getCouponConfigId();
            MemberCouponConfigEntity couponConfigEntity = memberCouponConfigService.getById(couponConfigId);
            LocalDateTime startTime = couponConfigEntity.getStartTime();
            LocalDateTime endTime = couponConfigEntity.getEndTime();
            Integer status = couponConfigEntity.getStatus();
            if (status!=1){
                throw new Exception("优惠券配置异常");
            }
            boolean between = TimeUtils.between(startTime, endTime, consumeDTO.getOrderTime());
            if (!between){
                throw new Exception("优惠券已过期");
            }
            Integer type = couponConfigEntity.getType();
            if (type==1 || type==2){
                //满减券 ,定额有门槛券
                Long ruleFull = couponConfigEntity.getRuleFull();
                if (ruleFull>orderAmt){
                    throw new Exception("订单金额不足无法使用优惠券");
                }
                realAmt = orderAmt<couponConfigEntity.getRuleSubtract()?0 : orderAmt -couponConfigEntity.getRuleSubtract();
            } else if (type==3){
                //定额无门槛券
                realAmt = orderAmt<couponConfigEntity.getRuleSubtract()?0 : orderAmt -couponConfigEntity.getRuleSubtract();
            }else {
                throw new Exception("优惠券类型不存在");
            }
        }
        if (memberMerchantId == null){
            throw new Exception("商户会员id为空");
        }
        MemberMerchantEntity currentUser = memberMerchantService.getById(memberMerchantId);
        if (currentUser==null){
            throw new Exception("商户会员不存在");
        }
        MemberMerchantEntity memberMerchantEntity = new MemberMerchantEntity();
        memberMerchantEntity.setId(memberMerchantId);
        memberMerchantEntity.setBalance(currentUser.getBalance()-realAmt);
        memberMerchantService.updateById(memberMerchantEntity);

        MemberAccountRecordEntity memberAccountRecordEntity = new MemberAccountRecordEntity();
        memberAccountRecordEntity.setMemberMerchantId(consumeDTO.getMemberMerchantId());
        memberAccountRecordEntity.setAmount(-realAmt);//消费金额
        memberAccountRecordEntity.setOrderTime(consumeDTO.getOrderTime());
        memberAccountRecordEntity.setPayType(consumeDTO.getPayType());
        if (activityConfigDetailId!=null || couponId!=null){
            memberAccountRecordEntity.setDiscountFlag(true);//是否有优惠
            memberAccountRecordEntity.setDiscountAmt(orderAmt - realAmt);
        }else {
            memberAccountRecordEntity.setDiscountFlag(false);//是否有优惠
        }
        //账户变动类型1-用户充值 2-用户消费 3-平台充值 4-平台核销 5-退款
        memberAccountRecordEntity.setType(2);
        memberAccountRecordEntity.setOrderNo(orderNo);
        memberAccountRecordEntity.setShopCode(consumeDTO.getShopCode());
        memberAccountRecordEntity.setCurrentBalance(memberMerchantEntity.getBalance());
        memberAccountRecordService.save(memberAccountRecordEntity);
        return realAmt;
    }

    /**
     * 账户充值
     * @param rechargeDTO
     */
    @Transactional(rollbackFor = Throwable.class)
    public Long recharge(CMemberRechargeDTO rechargeDTO) throws Exception {
        Integer cardConfigDetailId = rechargeDTO.getCardConfigDetailId();
        Integer memberMerchantId = rechargeDTO.getMemberMerchantId();
        Long orderAmt = rechargeDTO.getAmt();
        Long realAmt = orderAmt.longValue();
        //充值金额
        if (cardConfigDetailId!=null){
            MemberCardConfigDetailEntity cardConfigDetailEntity = cardConfigDetailService.getById(cardConfigDetailId);
            if (cardConfigDetailEntity== null || cardConfigDetailEntity.getDeleted()==true){
                throw new Exception("会员卡充值活动配置不存在");
            }
            MemberCardConfigEntity memberCardConfigEntity = memberCardConfigService.getById(cardConfigDetailEntity.getCardConfigId());
            if (memberCardConfigEntity == null || memberCardConfigEntity.getDeleted()==true){
                throw new Exception("会员卡充值活动配置不存在");
            }
            Long defaultAmt = cardConfigDetailEntity.getDefaultAmt();
            if (defaultAmt>orderAmt){
                throw new Exception("充值金额未达到活动限制金额");
            }
            realAmt = orderAmt + cardConfigDetailEntity.getGiveAmt();
        }

        if (memberMerchantId == null){
            throw new Exception("商户会员id为空");
        }
        MemberMerchantEntity currentUser = memberMerchantService.getById(memberMerchantId);
        if (currentUser==null){
            throw new Exception("商户会员不存在");
        }

        MemberMerchantEntity memberMerchantEntity = new MemberMerchantEntity();
        memberMerchantEntity.setId(memberMerchantId);
        memberMerchantEntity.setBalance(currentUser.getBalance()+realAmt);
        memberMerchantService.updateById(memberMerchantEntity);

        MemberAccountRecordEntity memberAccountRecordEntity = new MemberAccountRecordEntity();
        memberAccountRecordEntity.setMemberMerchantId(rechargeDTO.getMemberMerchantId());
        memberAccountRecordEntity.setOrderNo(rechargeDTO.getOrderNo());
        memberAccountRecordEntity.setAmount(realAmt);//充值金额
        memberAccountRecordEntity.setOrderTime(rechargeDTO.getOrderTime());
        memberAccountRecordEntity.setPayType(rechargeDTO.getPayType());
        memberAccountRecordEntity.setDiscountFlag(cardConfigDetailId!=null);//是否有优惠
        memberAccountRecordEntity.setDiscountAmt(orderAmt - realAmt);
        memberAccountRecordEntity.setType(1);
        memberAccountRecordEntity.setCurrentBalance(memberMerchantEntity.getBalance());
        memberAccountRecordService.save(memberAccountRecordEntity);
        return realAmt;
    }

    /**
     * 退款返还账户余额
     * @param memberRefundDTO
     * @throws Exception
     */
    @Override
    public void refund(CMemberRefundDTO memberRefundDTO) throws Exception {
        String orderNo = memberRefundDTO.getOrderNo();
        Long refundAmt = memberRefundDTO.getRefundAmt();
        Integer memberMerchantId = memberRefundDTO.getMemberMerchantId();
        String shopCode = memberRefundDTO.getShopCode();
        if (memberMerchantId == null){
            throw new Exception("商户会员id为空");
        }
        MemberMerchantEntity currentUser = memberMerchantService.getById(memberMerchantId);
        if (currentUser==null){
            throw new Exception("商户会员不存在");
        }
        MemberMerchantEntity memberMerchantEntity = new MemberMerchantEntity();
        memberMerchantEntity.setId(memberMerchantId);
        memberMerchantEntity.setBalance(currentUser.getBalance()+refundAmt);
        memberMerchantService.updateById(memberMerchantEntity);

        MemberAccountRecordEntity memberAccountRecordEntity = new MemberAccountRecordEntity();
        memberAccountRecordEntity.setMemberMerchantId(memberMerchantId);
        memberAccountRecordEntity.setAmount(refundAmt);//退款金额
        memberAccountRecordEntity.setOrderTime(memberRefundDTO.getOrderTime());
        //账户变动类型1-用户充值 2-用户消费 3-平台充值 4-平台核销 5-退款
        memberAccountRecordEntity.setType(5);
        memberAccountRecordEntity.setOrderNo(orderNo);
        memberAccountRecordEntity.setShopCode(shopCode);
        memberAccountRecordEntity.setCurrentBalance(memberMerchantEntity.getBalance());
        memberAccountRecordService.save(memberAccountRecordEntity);
    }

    @Override
    public void scoreConsume(CMemberScoreConsumeDTO scoreConsumeDTO) throws Exception {
        String orderNo = scoreConsumeDTO.getOrderNo();
        Integer memberMerchantId = scoreConsumeDTO.getMemberMerchantId();
        LocalDateTime orderTime = scoreConsumeDTO.getOrderTime();
        Long score = scoreConsumeDTO.getScore();
        String shopCode = scoreConsumeDTO.getShopCode();
        if (memberMerchantId == null){
            throw new Exception("商户会员id为空");
        }
        MemberMerchantEntity currentUser = memberMerchantService.getById(memberMerchantId);
        if (currentUser==null){
            throw new Exception("商户会员不存在");
        }
        MemberInfoEntity memberInfoEntity = memberInfoService.getById(currentUser.getMemberInfoId());
        if (memberInfoService == null){
            throw new Exception("会员不存在");
        }
        Integer nowScore = memberInfoEntity.getScore();
        if (score>nowScore){
            throw new Exception("积分不足");
        }
        MemberInfoEntity updateMemberInfo = new MemberInfoEntity();
        updateMemberInfo.setId(memberInfoEntity.getId());
        updateMemberInfo.setScore(nowScore-score.intValue());
        memberInfoService.updateById(updateMemberInfo);



        MemberAccountScoreRecordEntity memberAccountScoreRecordEntity = new MemberAccountScoreRecordEntity();
        memberAccountScoreRecordEntity.setCurrentScore((long)updateMemberInfo.getScore());
        memberAccountScoreRecordEntity.setOrderNo(orderNo);
        memberAccountScoreRecordEntity.setOrderTime(orderTime);
        memberAccountScoreRecordEntity.setShopCode(shopCode);
        memberAccountScoreRecordEntity.setMemberMerchantId(memberMerchantId);
        memberAccountScoreRecordEntity.setScore(score);
        memberAccountScoreRecordEntity.setMemberInfoId(memberInfoEntity.getId());
        memberAccountScoreRecordEntity.setType(2);
        memberAccountScoreRecordService.save(memberAccountScoreRecordEntity);
    }

    @Override
    public void scoreGet() {

    }

}
